import { ChangeEvent, useCallback, useEffect, useMemo, useState } from "react";
import styles from "../style/app.module.less";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../store";
import { UserActionType, UserState } from "../store/userReducer";
import {
  HomeOutlined,
  LogoutOutlined,
  LoginOutlined,
  EditOutlined,
  SearchOutlined,
  UserOutlined,
} from "@ant-design/icons";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { Avatar, Dropdown, MenuProps } from "antd";
import request, { removeToken } from "../utils/request";
import React from "react";

const MyHeader: React.FC = () => {
  const dispatch = useDispatch();
  const user = useSelector<RootState, UserState>((state) => state.user);
  const keyword = useSelector<RootState, string>((state) => state.keyword);
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    async function fetchUserInfo() {
      const token = localStorage.getItem('TOKEN')
      if (token) {
        const result = await request(`/api/admin/whoami`)
        result.data.msg === '' && dispatch({
          type: UserActionType.SET_USER,
          payload: result.data.data
        })
      }
    }
    let timer = setTimeout(() => {
      fetchUserInfo()
    }, 500)
    return () => clearTimeout(timer)
  }, [dispatch])

  const handleLogout = () => {
    dispatch({
      type: UserActionType.RESET_USER,
      payload: {},
    });
    removeToken();
    navigate("/bloglist");
  };
  function handleSearch(): void {}
  function handleKeyworksChange(e: ChangeEvent<HTMLInputElement>): void {
    dispatch({
      type: 'keyword',
      value: e.target.value
    })
  }

  const isLogin = useMemo(() => {
    return user.userInfo.id > -1
  }, [user.userInfo.id]);
  const avatarItems: MenuProps["items"] = isLogin
    ? [
        {
          key: "1",
          icon: <HomeOutlined />,
          label: (
            <Link to={"/admin"} rel="noopener noreferrer">
              {user.userInfo.username}
            </Link>
          ),
        },
        {
          key: "2",
          icon: <EditOutlined />,
          label: (
            <Link to={"/blog"} rel="noopener noreferrer">
              写笔记
            </Link>
          ),
        },
        {
          key: "3",
          icon: <LogoutOutlined />,
          label: <div onClick={handleLogout}>登出</div>,
        },
      ]
    : [
        {
          key: "1",
          icon: <LoginOutlined />,
          label: (
            <Link to={"/login"} rel="noopener noreferrer">
              登录
            </Link>
          ),
        },
      ];
  const menuClass = useCallback((path: string) => {
    return location.pathname === path ? styles.active : ''
  }, [location.pathname])
  return (
    <header className={styles.header}>
      <div className={styles.logo}>
        <h1>贝语斛</h1>
      </div>
      <div className={styles.menu}>
        <Link to={"/bloglist"} className={menuClass('/bloglist')}>
          笔记
        </Link>
        <Link to={"/practice"} className={menuClass('/practice')}>
          炫酷的
        </Link>
        <Link to={"/files"} className={menuClass('/files')} style={isLogin ? {} : {display: 'none'}}>
          文件
        </Link>
        <Link to={"/admin"} className={menuClass('/admin')}>
          关于我
        </Link>
      </div>
      <div className={styles.searchArea}>
        <div className={styles.searchBtn}>
          <SearchOutlined onClick={handleSearch} />
        </div>
        <input
          className={styles.keyword}
          value={keyword}
          onChange={(e) => handleKeyworksChange(e)}
          type="text"
        />
      </div>
      <Dropdown menu={{ items: avatarItems }} placement="bottomRight" arrow>
        {isLogin ? (
          <Avatar
            size={56}
            style={{minWidth: 56}}
            src={<img src={user.userInfo.avatar} alt="avatar" />}
          />
        ) : (
          <Avatar size={56} style={{minWidth: 56}} icon={<UserOutlined />} />
        )}
      </Dropdown>
    </header>
  );
};

export default React.memo(MyHeader);
